"""
Celery任务模块
定义后台异步任务和定时任务
"""
from celery import shared_task
from django.db import transaction
from django.utils import timezone
from .models import Host, PasswordHistory, DailyStat
import secrets
import logging

logger = logging.getLogger(__name__)

@shared_task(bind=True, max_retries=3)
def rotate_passwords(self):
    """
    密码轮换任务（每8小时执行）
    流程：
    1. 生成新随机密码
    2. 将旧密码存入历史记录
    3. 更新主机密码字段
    """
    try:
        with transaction.atomic():
            for host in Host.objects.select_for_update().all():
                new_pwd = secrets.token_urlsafe(16)
                PasswordHistory.objects.create(
                    host=host,
                    password=host.root_password
                )
                host.root_password = new_pwd
                host.save()
        logger.info("密码轮换任务完成，共处理%d台主机", Host.objects.count())
    except Exception as e:
        logger.error("密码轮换失败: %s", str(e))
        self.retry(countdown=300)  # 5分钟后重试

@shared_task
def daily_stats():
    """
    每日统计任务（每天0点执行）
    生成每个IDC的主机数量统计快照
    """
    stats = Host.objects.values('idc__city', 'idc').annotate(total=Count('id'))
    for stat in stats:
        DailyStat.objects.create(
            city_id=stat['idc__city'],
            idc_id=stat['idc'],
            host_count=stat['total']
        )